import React, { useEffect, useRef, useState } from 'react'
import { DeleteOutlined, UnorderedListOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Table, Button, Modal, Switch, Form, Input, Select } from 'antd'
import axios from 'axios'
const { confirm } = Modal
export default function UserList() {
    const [dataSource, setdataSource] = useState([])
    const [isAddvisable, setisAddvisable] = useState(false)
    const [rolesList, setrolesList] = useState([])
    const [regionList, setregionList] = useState([])
    const [disabled, setdisabled] = useState(false)

    const [isEdit, setisEdit] = useState(false)
    const [currId, setcurrId] = useState(null)
    const { roleId, region } = JSON.parse(localStorage.getItem('token'))
    useEffect(() => {
        query()
    }, [])

    useEffect(() => {
        axios.get('/roles').then(res => {
            const list = res.data.map(item => {
                return {
                    value: item.id,
                    label: item.roleName,
                    disabled: roleIsDisabled(item),

                }
            })
            setrolesList(list)
        })
    }, [])

    useEffect(() => {
        axios.get('/regions').then(res => {
            const list = res.data.map(item => {
                return {
                    value: item.title,
                    label: item.value,
                    disabled: regionIsDisabled(item),
                }
            })
            setregionList(list)
        })
    }, [])


    const query = () => {
        axios.get('/users?_expand=role').then(res => {
            let list = res.data.filter(item => item.roleId >= roleId)
            setdataSource(list)
        })
    }
    const columns = [
        {
            title: '区域',
            dataIndex: 'region',
            filters: [
                ...regionList.map(item => {
                    return {
                        text: item.title,
                        value: item.value
                    }
                }),
                {
                    text: '全球',
                    value: '全球'
                }
            ],
            onFilter: (value, item) => {
                if (value === '全球') return item.region === ''
                return item.region === value
            },
            render: (region) => <b>{region || '全球'}</b>
        },
        {
            title: '角色名称',
            dataIndex: 'role',
            render: (role) => <b>{role.roleName}</b>
        },
        {
            title: '用户名',
            dataIndex: 'username',

        },
        {
            title: '用户状态',
            dataIndex: 'roleState',
            render: (roleState, item) => <Switch onChange={() => roleStateChange(item)} disabled={item.default} checked={roleState}></Switch>
        },
        {
            title: '操作',
            render: (item) => {
                return <div>
                    <Button onClick={() => handelUpdate(item)} disabled={item.default} style={{ margin: '4px' }} type="primary" shape="circle" icon={<UnorderedListOutlined />} />

                    <Button onClick={() => confirmMethod(item)} style={{ margin: '4px' }} type="danger" shape="circle" icon={<DeleteOutlined />} />
                </div >
            }
        },
    ]

    const confirmMethod = (item) => {
        confirm({
            title: '您确定要删除掉吗',
            icon: <ExclamationCircleOutlined />,
            content: '一旦删除将不可恢复',
            onOk() {
                deleteReady(item)
            },
            onCancel() {

            },
        });
    }
    const deleteReady = (item) => {
        axios.delete(`/users/${item.id}`).then(() => {
            query()
        })
    }

    const roleStateChange = (item) => {
        item.roleState = !item.roleState
        setdataSource([...dataSource])
        axios.patch(`/users/${item.id}`, {
            roleState: item.roleState
        })
    }
    const handelUpdate = (item) => {
        setisEdit(true)
        setisAddvisable(true)
        //将数据注入
        form.setFieldsValue(item)
        setcurrId(item.id)
    }
    const onCancel = () => {
        setisAddvisable(false)
        form.resetFields();
    }

    const addForm = () => {
        form
            .validateFields()
            .then(values => {
                setdisabled(false)
                //后端生成id再添加

                axios.post('/users', {
                    ...values,
                    'roleState': true,
                    'default': false
                }).then(res => {
                    query()
                    form.resetFields();
                    setisAddvisable(false)
                })

            })
            .catch(info => {
                console.log('错误信息:', info);
            });
    }

    const editForm = () => {
        form
            .validateFields()
            .then(values => {
                axios.patch(`/users/${currId}`, values).then(res => {
                    query()
                    form.resetFields();
                    setisAddvisable(false)
                })

            })
            .catch(info => {
                console.log('错误信息:', info);
            });
    }

    const regionIsDisabled = (value) => {
        if (isEdit) {
            if (roleId === '1') return false
            return true
        }
        if (roleId === '1') return false
        return region !== value.value
    }

    const roleIsDisabled = (value) => {
        return value.id < roleId
    }

    const [form] = Form.useForm();
    const formRefs = useRef()
    return (
        <div>
            <Button type={'primary'} onClick={
                () => setisAddvisable(true)
            }>添加用户</Button>
            <Table dataSource={dataSource} columns={columns} pagination={{
                pageSize: 10
            }} rowKey={(item) => item.id} />

            <Modal
                open={isAddvisable}
                title={isEdit ? "修改用户" : "添加用户"}
                okText={isEdit ? "修改" : "添加"}
                cancelText="取消"
                onCancel={onCancel}
                onOk={() => isEdit ? editForm() : addForm()}
            >
                <Form
                    form={form}
                    ref={formRefs}
                    layout="vertical"
                    name="form_in_modal"
                    initialValues={{ modifier: 'public' }}
                >
                    <Form.Item
                        name="username"
                        label="用户名"
                        rules={[{ required: true, message: '请填写你的用户名' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item name="password" label="密码" rules={[{ required: true, message: '请填写你的密码' }]}>
                        <Input type='password' />
                    </Form.Item>
                    <Form.Item name="roleId" label="角色" rules={disabled ? [] : [{ required: true, message: '请选择你的角色' }]}>
                        <Select
                            onChange={(value) => {

                                setdisabled(value === 1 ? true : false)
                                if (value === 1) {
                                    formRefs.current.setFieldsValue({ region: '' })
                                }
                            }}
                            options={rolesList}
                        />
                    </Form.Item>
                    <Form.Item name="region" label="区域" rules={[{ required: true, message: '请选择你的区域' }]}>
                        <Select
                            disabled={disabled}
                            options={regionList}
                        />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    )
}

